
import { _decorator, Component, Node, Sprite, SpriteFrame } from 'cc';
import { ItemStatusEnum, ItemTypeEnum } from '../../Enum';
import DataManager from '../Runtime/DataManager';
import { RenderManager } from '../Base/RenderManager';
const { ccclass, property } = _decorator;


@ccclass('ItemManager')
export class ItemManager extends RenderManager {
    label: string;
    status: ItemStatusEnum;
    type: ItemTypeEnum

    @property(SpriteFrame)
    sceneSF: SpriteFrame = null;

    @property(SpriteFrame)
    inventorySF: SpriteFrame = null;



    start() {
        super.start()
        this.node.on(Node.EventType.TOUCH_END, this.touchEnd, this);
    }

    protected onDestroy(): void {
        this.node.off(Node.EventType.TOUCH_END, this.touchEnd, this);
    }

    render(): void {
        // 检查节点是否有效，如果节点已被销毁则直接返回
        if (!this.node || !this.node.isValid) {
            return;
        }
        const status = DataManager.Instance.items.find(i => i.type === this.type)?.status
        const spriteCompnent = this.getComponent(Sprite);
        // 检查 Sprite 组件是否存在
        if (!spriteCompnent) {
            return;
        }
        switch (status) {
            case ItemStatusEnum.Scene:
                this.node.active = true;
                spriteCompnent.spriteFrame = this.sceneSF;
                break;
            case ItemStatusEnum.Inventory:
                this.node.active = true;
                spriteCompnent.spriteFrame = this.inventorySF;
                break;
            case ItemStatusEnum.DISABLED:
                this.node.active = false;
                break;
            default:
                break;
        }
    }

    touchEnd() {
        const item = DataManager.Instance.items.find(i => i.type === this.type)
        if (!item) {
            return;
        }
        //如果物品在场景中被点击,则物品的状态变化为在背包里
        if (item.status === ItemStatusEnum.Scene) {
            item.status = ItemStatusEnum.Inventory;
            DataManager.Instance.items = [...DataManager.Instance.items]
        } else if (item.status === ItemStatusEnum.Inventory) {
            //如果物品已经在背包中，点击时切换当前选中的物品类型，触发渲染
            DataManager.Instance.currItemType = this.type;
        }
    }

}

